package com.wht.bill.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bigkoo.pickerview.TimePickerView;
import com.wht.bill.R;
import com.wht.bill.adapter.ClassifyRankAdapter;
import com.wht.bill.bean.BillBean;
import com.wht.bill.bean.TypeBean;
import com.wht.bill.utils.CacheUtils;
import com.wht.bill.utils.DateUtils;
import com.wht.bill.utils.FormatUtils;
import com.wht.bill.utils.NumberUtils;
import com.wht.bill.utils.PieChartUtil;
import com.wht.bill.view.CircleImageView;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 记账本--类别报表
 */
public class MenuTypeFragment extends BaseFragment
        implements OnChartValueSelectedListener {


    @BindView(R.id.chart)
    PieChart mChart;
    @BindView(R.id.center_title)
    TextView centerTitle;
    @BindView(R.id.tv1)
    TextView tv1;
    @BindView(R.id.center_money)
    TextView centerMoney;
    @BindView(R.id.layout_center)
    LinearLayout layoutCenter;
    @BindView(R.id.center_img)
    ImageView centerImg;
    @BindView(R.id.data_year)
    TextView dataYear;
    @BindView(R.id.data_month)
    TextView dataMonth;
    @BindView(R.id.layout_data)
    LinearLayout layoutData;
    @BindView(R.id.cash_surplus)
    TextView cashSurplus;
    @BindView(R.id.circle_bg)
    CircleImageView circleBg;
    @BindView(R.id.circle_img)
    ImageView circleImg;
    @BindView(R.id.layout_circle)
    RelativeLayout layoutCircle;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.rank_title)
    TextView rankTitle;


    @BindView(R.id.swipe)
    SwipeRefreshLayout swipe;
    @BindView(R.id.item_type)
    RelativeLayout itemType;

    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.layout_typedata)
    LinearLayout layoutTypedata;

    private boolean TYPE = true;//默认总收入true
    private List<TypeBean.TMoneyBean> tMoneyBeanList;
    private String type_name;
    private String back_color;

    private ClassifyRankAdapter adapter;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_menu_type;
    }


    @Override
    protected void initEventAndData() {

        PieChartUtil.initPieChart(mChart);
        mChart.setOnChartValueSelectedListener(this);

        dataYear.setText(DateUtils.getCurYear("yyyy"));
        dataMonth.setText(DateUtils.date2Str(new Date(), "MM"));
        //改变加载显示的颜色
        swipe.setColorSchemeColors(getResources().getColor(R.color.text_red), getResources().getColor(R.color.text_red));
        //设置向下拉多少出现刷新
        swipe.setDistanceToTriggerSync(200);
        //设置刷新出现的位置
        swipe.setProgressViewEndTarget(false, 200);
        swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                swipe.setRefreshing(false);
                setReportData();
                PieChartUtil.setAnimate(mChart);

            }
        });


        rvList.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new ClassifyRankAdapter();
        rvList.setAdapter(adapter);

        setReportData();
    }

    /**
     * 组装数据
     *
     * @param isOutcome 是否是支出
     */
    private TypeBean assembleData(boolean isOutcome) {
        //获取账单
        List<BillBean> billList = CacheUtils.getBillList();
        //组装数据
        TypeBean typeBean = new TypeBean();
        typeBean.total = "0.00";
        //当月账单
        List<BillBean> currentMonthList = new ArrayList<>();
        if (billList != null && !billList.isEmpty()) {
            for (BillBean billBean : billList) {
                //筛选出当月的数据
                if (TextUtils.equals(dataYear.getText().toString(), billBean.time.split("-")[0])
                        && TextUtils.equals(dataMonth.getText().toString(), billBean.time.split("-")[1]) && TextUtils.equals(isOutcome ? "1" : "2", billBean.billType)) {
                    currentMonthList.add(billBean);
                }
            }
        }
        double total = 0;
        List<TypeBean.TMoneyBean> classifyData = new ArrayList<>();
        if (!currentMonthList.isEmpty()) {
            for (BillBean currentBillBean : currentMonthList) {
                total += NumberUtils.string2Double(currentBillBean.money);
                //先判断是否有某一分类的数据
                boolean isContainsTarget = false;
                for (TypeBean.TMoneyBean tMoneyBean : classifyData) {
                    if (TextUtils.equals(currentBillBean.classification, tMoneyBean.classifyName)) {
                        isContainsTarget = true;
                        //有,直接添加
                        tMoneyBean.billList.add(currentBillBean);
                        tMoneyBean.classifyMoney = String.format("%.2f", NumberUtils.add(tMoneyBean.classifyMoney, currentBillBean.money));
                        break;
                    }
                }
                //如果没有
                if (!isContainsTarget) {
                    TypeBean.TMoneyBean bean = new TypeBean.TMoneyBean();
                    bean.classifyMoney = currentBillBean.money;
                    bean.classifyName = currentBillBean.classification;
                    bean.classifyBackgroundColor = PieChartUtil.getTypeColor(currentBillBean.classification);
                    bean.billList.add(currentBillBean);
                    classifyData.add(bean);
                }
            }
        }
        typeBean.total = String.format("%.2f", total);
        typeBean.classifyList.addAll(classifyData);

        return typeBean;
    }


    private void setReportData() {
        TypeBean typeModel = assembleData(TYPE);
        if (TYPE) {
            centerTitle.setText("总支出");
            tv1.setText("总支出");
            centerImg.setImageResource(R.mipmap.tallybook_output);
            centerMoney.setTextColor(Color.parseColor("#05B092"));
            cashSurplus.setTextColor(Color.parseColor("#05B092"));

        } else {
            centerTitle.setText("总收入");
            tv1.setText("总收入");
            centerImg.setImageResource(R.mipmap.tallybook_input);
            centerMoney.setTextColor(Color.parseColor("#FF4B4B"));
            cashSurplus.setTextColor(Color.parseColor("#FF4B4B"));

        }
        if (typeModel == null) {
            return;
        }
        //结余
        //cashSurplus.setText(typeModel.getSurplus());
        //总支出/总收入
        centerMoney.setText(getMoneyStr(NumberUtils.string2Double(typeModel.total)));
        cashSurplus.setText(getMoneyStr(NumberUtils.string2Double(typeModel.total)));
        tMoneyBeanList = typeModel.classifyList;

        ArrayList<PieEntry> entries = new ArrayList<PieEntry>();
        ArrayList<Integer> colors = new ArrayList<Integer>();

        if (tMoneyBeanList != null && !tMoneyBeanList.isEmpty()) {
            layoutTypedata.setVisibility(View.VISIBLE);
            for (int i = 0; i < tMoneyBeanList.size(); i++) {
                float scale = NumberUtils.div(tMoneyBeanList.get(i).classifyMoney,typeModel.total).floatValue();
                float value = Math.max(scale, 0.06f);
                entries.add(new PieEntry(value, PieChartUtil.getTypeDrawable(tMoneyBeanList.get(i).classifyName)));
                colors.add(Color.parseColor(tMoneyBeanList.get(i).classifyBackgroundColor));
            }
            setNoteData(0);
        } else {//无数据时的显示
            layoutTypedata.setVisibility(View.GONE);
            entries.add(new PieEntry(1f));
            colors.add(0xffAAAAAA);
        }

        PieChartUtil.setPieChartData(mChart, entries, colors);
    }

    /**
     * 点击饼状图上区域后相应的数据设置
     *
     * @param index
     */
    private void setNoteData(int index) {
        type_name = tMoneyBeanList.get(index).classifyName;
        back_color = tMoneyBeanList.get(index).classifyBackgroundColor;
        if (TYPE) {
            money.setText("-" + getMoneyStr(NumberUtils.string2Double(tMoneyBeanList.get(index).classifyMoney)));
        } else {
            money.setText("+" + getMoneyStr(NumberUtils.string2Double(tMoneyBeanList.get(index).classifyMoney)));
        }
        title.setText(type_name);
        rankTitle.setText(type_name + "排行榜");
        circleBg.setImageDrawable(new ColorDrawable(Color.parseColor(back_color)));
        circleImg.setImageDrawable(PieChartUtil.getTypeDrawable(type_name));
        Collections.sort(tMoneyBeanList.get(index).billList, new Comparator<BillBean>() {
            @Override
            public int compare(BillBean p1, BillBean p2) {
                return Double.compare(NumberUtils.string2Double(p2.money), NumberUtils.string2Double(p1.money));
            }
        });
        adapter.setList(tMoneyBeanList.get(index).billList);
        adapter.notifyDataSetChanged();
    }


    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;
        int entryIndex = (int) h.getX();
        PieChartUtil.setRotationAngle(mChart, entryIndex);
        setNoteData(entryIndex);
    }


    @Override
    public void onNothingSelected() {
        Log.i("PieChart", "nothing selected");
    }


    @OnClick({R.id.layout_center, R.id.layout_data, R.id.item_type})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_center:

                if (TYPE) {
                    TYPE = false;
                } else {
                    TYPE = true;
                }
                setReportData();

                break;
            case R.id.layout_data:
                //时间选择器
                new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {//选中事件回调
                        dataYear.setText(DateUtils.date2Str(date, "yyyy"));
                        dataMonth.setText(DateUtils.date2Str(date, "MM"));
                        setReportData();
                        PieChartUtil.setAnimate(mChart);
                    }
                })
                        .setRangDate(null, Calendar.getInstance())
                        .setType(new boolean[]{true, true, false, false, false, false})
                        .build()
                        .show();
                break;
            case R.id.item_type:
                break;

        }
    }


    private String getMoneyStr(double money) {
        return FormatUtils.MyDecimalFormat("##,###,###.##", money);
    }

}
